﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using UnityEngine;

/// <summary>
/// 对 MonoBehaviour 进行封装，添加自定义的功能
/// </summary>
public class USaBehaviour : MonoBehaviour
{
#if UNITY_EDITOR

    /// <summary>
    /// 根据字段名匹配gameobject.name，对字段进行序列化
    /// </summary>
    [ContextMenu("自动分配字段")]
    public void AssignVariableByObjectName()
    {
        Regex reg = new Regex("^[a-zA-Z][a-zA-Z0-9_]+$");
        // 获取类中所有需被序列化的字段
        List<FieldInfo> infos = GetType().GetFields().Where(f => f.FieldType.IsSubclassOf(typeof(Component))).ToList();
        List<Transform> trans = GetComponentsInChildren<Transform>().Where(t => reg.IsMatch(t.name)).ToList();
        foreach (var info in infos)
        {
            // 获取当前物体中的组件
            Component comp = GetComponent(info.FieldType);
            if (comp != null && comp.name.Replace("_", "").ToLowerInvariant().Equals(info.Name.Replace("_", "").ToLowerInvariant()))
            {
                info.SetValue(this, comp);
                break;
            }
            // 获取子物体中的组件
            foreach (var tran in trans)
            {
                comp = tran.GetComponent(info.FieldType);
                if (comp != null && comp.name.Replace("_", "").ToLowerInvariant().Equals(info.Name.Replace("_", "").ToLowerInvariant()))
                {
                    info.SetValue(this, comp);
                    break;
                }
            }
        }
    }

#endif
}